package com.ibs.hadoop.hbase.service.run;

import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * 构造通用的结果结果缓存
 * 
 * @author Administrator
 * 
 * @param <A>
 * @param <V>
 */
public class QueryExecuteWaitCache<A, V> implements ExecuteQuery<A, V> {

    /**
     * 缓存 队列
     */
    private final ConcurrentMap<String, Future<V>> cache = new ConcurrentHashMap<String, Future<V>>();

    /**
     * 通用计算接口
     */
    private final ExecuteQuery<A, V> comp1;

    public QueryExecuteWaitCache(ExecuteQuery<A, V> comp1) {
        this.comp1 = comp1;
    }

    public V execute(final String flow, final A arg) throws InterruptedException {
        while (true) {
            Future<V> f = cache.get(flow);

            if (f == null) {
                Callable<V> eval = new Callable<V>() {

                    @Override
                    public V call() throws Exception {
                        return comp1.execute(flow, arg);
                    }
                };

                FutureTask<V> ft = new FutureTask<V>(eval);

                f = cache.put(flow, ft);

                if (f == null) {
                    f = ft;
                    ft.run();
                }
            }

            try {
                return f.get();
            }
            // 如果计算取消
            catch (CancellationException e1) {
                e1.printStackTrace();
                cache.remove(arg);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

    }

}
